package com.chengyu.core.service.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.ServicesEnums;
import com.chengyu.core.domain.form.ServicesImportForm;
import com.chengyu.core.domain.form.ServicesPublishForm;
import com.chengyu.core.domain.form.ServicesSearchForm;
import com.chengyu.core.domain.result.*;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.*;
import com.chengyu.core.model.*;
import com.chengyu.core.service.services.ServicesCateService;
import com.chengyu.core.service.services.ServicesService;
import com.chengyu.core.service.shop.ShopCateService;
import com.chengyu.core.util.ValidateUtil;
import com.chengyu.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @title  商品管理
 * @author wenlj
 * @date   2023/10/03
 */
@Service
public class ServicesServiceImpl implements ServicesService {

	@Autowired
	private PmsServicesMapper servicesMapper;
	@Autowired
	private PmsServicesSkuMapper servicesSkuMapper;
	@Autowired
	private BaseMapper baseMapper;
	@Autowired
	private PmsServicesGroupMapper servicesGroupMapper;
	@Autowired
	private ServicesCateService servicesCateService;
	@Autowired
	private ShopCateService shopCateService;
	@Autowired
	private PmsServicesAttrKeyMapper servicesAttrKeyMapper;
	@Autowired
	private PmsServicesAttrValMapper servicesAttrValMapper;
	@Autowired
	private CustomServicesMapper customServicesMapper;
	@Autowired
	private TradeStorageStockMapper tradeStorageStockMapper;

	@Override
	public List<PmsServices> getServicesList(ServicesSearchForm form, Integer page, Integer pageSize) {
		PageHelper.startPage(page, pageSize);

		//使用全文检索
		return customServicesMapper.getServicesList(form);
		/*PmsServicesExample example = new PmsServicesExample();
		if(StringUtils.isNotBlank(form.getSort())){
			example.setOrderByClause(form.getSort());
		}else{
			example.setOrderByClause("sort asc, weight desc, id desc");
		}
		PmsServicesExample.Criteria criteria = example.createCriteria();
		criteria.andStatusNotEqualTo(ServicesEnums.ServicesStatus.DEL.getValue());
		if(form.getQueryPlatformServices()) {
			criteria.andShopIdEqualTo(0);
		} else {
			criteria.andShopIdNotEqualTo(0);
		}
		if(form.getShopId() != null){
			criteria.andShopIdEqualTo(form.getShopId());
		}
		if(form.getCateId() != null){
			criteria.andCateIdEqualTo(form.getCateId());
		}
		if(form.getCatePid() != null){
			criteria.andCatePidEqualTo(form.getCatePid());
		}
		if(form.getCateTid() != null){
			criteria.andCateTidEqualTo(form.getCateTid());
		}
		if(form.getShopCateId() != null){
			criteria.andShopCateIdEqualTo(form.getShopCateId());
		}
		if(form.getShopCatePid() != null){
			criteria.andShopCatePidEqualTo(form.getShopCatePid());
		}
		if(form.getShopCateTid() != null){
			criteria.andShopCateTidEqualTo(form.getShopCateTid());
		}
		if(StringUtils.isNotBlank(form.getTitle())){
			criteria.andTitleLike("%"+form.getTitle()+"%");
		}
		if(form.getStatus() != null){
			criteria.andStatusEqualTo(form.getStatus());
		}
		if(form.getType() != null){
			criteria.andTypeEqualTo(form.getType());
		}
		if(CollectionUtil.isNotEmpty(form.getCatePidList())){
			criteria.andCatePidIn(form.getCatePidList());
		}
		if(form.getMinAmount() != null){
			criteria.andPriceGreaterThanOrEqualTo(form.getMinAmount());
		}
		if(form.getMaxAmount() != null){
			criteria.andPriceLessThanOrEqualTo(form.getMaxAmount());
		}
		return servicesMapper.selectByExample(example);*/
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void publishServices(UmsShop shop, ServicesPublishForm publishForm) throws ServiceException {
		PmsServices services = new PmsServices();
		BeanUtil.copyProperties(publishForm, services);
		Integer tempServicesId = services.getId();
		services.setShopId(shop.getId());
		services.setShopName(shop.getName());
		String[] cateIdList = publishForm.getServicesCateIds().split(CommonConstant.DH_REGEX);
		services.setCatePid(Integer.parseInt(cateIdList[0]));
		if(cateIdList.length >=2 ){
			services.setCateTid(Integer.parseInt(cateIdList[1]));
		}
		if(cateIdList.length >=3){
			services.setCateId(Integer.parseInt(cateIdList[2]));
		}


		if(cateIdList.length >=0) {
			services.setCateId(Integer.parseInt(cateIdList[cateIdList.length - 1]));
		}


		services.setCateIds(publishForm.getServicesCateIds());
		services.setCateName(servicesCateService.getServicesCateName(CollectionUtil.newArrayList(services.getCatePid(), services.getCateTid(), services.getCateId())));

//		//商品库商品不需要此字段
//		if(shop.getId() != 0) {
//			String[] shopCateIdList = publishForm.getShopCateIds().split(CommonConstant.DH_REGEX);
//			services.setShopCatePid(Integer.parseInt(shopCateIdList[0]));
//			if(shopCateIdList.length >=2 ){
//				services.setShopCateTid(Integer.parseInt(shopCateIdList[1]));
//			}
//			if(shopCateIdList.length >=3){
//				services.setShopCateId(Integer.parseInt(shopCateIdList[2]));
//			}
//			services.setShopCateIds(publishForm.getShopCateIds());
//			services.setShopCateName(shopCateService.getServicesCateName(CollectionUtil.newArrayList(services.getShopCatePid(), services.getShopCateTid(), services.getShopCateId())));
//		}
		services.setSort(99);
//		services.setWeight(0);
		services.setUpdTime(DateUtil.date());
		if(services.getId() == null){
			services.setAddTime(services.getUpdTime());
			servicesMapper.insertSelective(services);
		}else{
			servicesMapper.updateByPrimaryKeySelective(services);
		}

		//团购
		if(CollectionUtil.isNotEmpty(publishForm.getGroupList())){
			for(PmsServicesGroup group : publishForm.getGroupList()){
				group.setServicesId(services.getId());
				if(group.getId() == null){
					servicesGroupMapper.insertSelective(group);
				}else{
					servicesGroupMapper.updateByPrimaryKeySelective(group);
				}
			}
		}

		//SKU
		if(StringUtils.isBlank(publishForm.getAttrKeyList()) || StringUtils.isBlank(publishForm.getSkuList())){
			throw new ServiceException("请填写完整的产品属性");
		}
		List<Integer> extraDelKeyId = new ArrayList<>();
		List<ServicesAttrKeyResult> attrKeyList = JSONArray.parseArray(publishForm.getAttrKeyList(), ServicesAttrKeyResult.class);
		Map<String,Integer> tempMap = new HashMap<>();
		int keyIndex = 0;
		for(ServicesAttrKeyResult attrKey : attrKeyList){
			//KEY
			if(StringUtils.isBlank(attrKey.getAttrKey()) || StringUtils.isBlank(attrKey.getAttrValueList())){
				throw new ServiceException("请填写完整的产品属性");
			}
			PmsServicesAttrKey servicesAttrKey = this.getServicesAttrKey(tempServicesId, attrKey.getAttrKey());
			if(servicesAttrKey == null){
				servicesAttrKey = new PmsServicesAttrKey();
			}
			Integer tempKeyId = servicesAttrKey.getId();
			servicesAttrKey.setServicesId(services.getId());
			servicesAttrKey.setName(attrKey.getAttrKey());
			if(servicesAttrKey.getId() == null){
				servicesAttrKeyMapper.insertSelective(servicesAttrKey);
			}else{
				servicesAttrKeyMapper.updateByPrimaryKeySelective(servicesAttrKey);
			}
			//VALUE
			List<String> valueList = JSONArray.parseArray(attrKey.getAttrValueList(), String.class);
			for(String value : valueList){
				if(StringUtils.isBlank(value)){
					throw new ServiceException("请填写完整的产品属性");
				}
				PmsServicesAttrVal servicesAttrVal = this.getServicesAttrValue(tempServicesId, tempKeyId, value);
				if(servicesAttrVal == null){
					servicesAttrVal = new PmsServicesAttrVal();
				}
				servicesAttrVal.setServicesId(services.getId());
				servicesAttrVal.setAttrKeyId(servicesAttrKey.getId());
				servicesAttrVal.setAttrKeyName(servicesAttrKey.getName());
				servicesAttrVal.setValue(value);
				if(servicesAttrVal.getId() == null){
					servicesAttrValMapper.insertSelective(servicesAttrVal);
				}else{
					servicesAttrValMapper.updateByPrimaryKeySelective(servicesAttrVal);
				}
				tempMap.put(keyIndex+"-"+value, servicesAttrVal.getId());
			}
			keyIndex++;
			extraDelKeyId.add(servicesAttrKey.getId());
		}

		List<String[]> skuList = JSONArray.parseArray(publishForm.getSkuList(), String[].class);
		if(CollectionUtil.isEmpty(skuList)){
			throw new ServiceException("请填写完整的产品属性");
		}
		List<String> extraDelSku = new ArrayList<>();
		for(String[] skuArr : skuList){
			int length = skuArr.length;
			ValidateUtil.validateNull(new Object[]{skuArr[length-3], skuArr[length-4], skuArr[length-5], skuArr[length-6]},
					"重量不能为空", "库存不能为空", "现价不能为空", "原价不能为空");

			//attrKeyList: [{"attrKey":"颜色","attrValue":"","attrValueList":["黑","白"]},{"attrKey":"尺寸","attrValue":"","attrValueList":["大","小"]}]
			//skuList: [["黑","大","","222","999","888","",""],["黑","小","","222","999","888","",""],["白","大","","222","999","888","",""],["白","小","","222","999","888","",""]]
			StringBuilder attrSymbolPath = new StringBuilder();
			StringBuilder attrSymbolName = new StringBuilder();
			for(int i = 0; i < length-6; i++){
				attrSymbolPath.append("/");
				attrSymbolPath.append(tempMap.get(i+"-"+skuArr[i]));

				attrSymbolName.append("/");
				attrSymbolName.append(skuArr[i]);
			}
			PmsServicesSku servicesSku = this.getServicesSku(tempServicesId, attrSymbolPath.substring(1));
			if(servicesSku == null){
				servicesSku = new PmsServicesSku();
			}
			servicesSku.setServicesId(services.getId());
			servicesSku.setAttrSymbolPath(attrSymbolPath.substring(1));
			servicesSku.setAttrSymbolName(attrSymbolName.substring(1));
			servicesSku.setOriPrice(new BigDecimal(skuArr[length-6]));
			servicesSku.setPrice(new BigDecimal(skuArr[length-5]));
			servicesSku.setStock(Integer.parseInt(skuArr[length-4]));
			servicesSku.setWeight(new BigDecimal(skuArr[length-3]));
			servicesSku.setSkuNo(skuArr[length-2]);
			servicesSku.setImg(skuArr[length-1]);
			if(StringUtils.isBlank(servicesSku.getImg())){
				servicesSku.setImg(services.getMainImg());
			}
			if(StringUtils.isBlank(servicesSku.getSkuNo())){
				servicesSku.setSkuNo("LEK"+StringUtils.genOrderNo(0));
			}
			if(servicesSku.getId() == null){
				servicesSkuMapper.insertSelective(servicesSku);
			}else{
				servicesSkuMapper.updateByPrimaryKeySelective(servicesSku);
			}
			extraDelSku.add(servicesSku.getAttrSymbolPath());
		}
		PmsServices updateServices = new PmsServices();
		updateServices.setId(services.getId());
		updateServices.setPrice(new BigDecimal(skuList.get(0)[skuList.get(0).length-5]));
		servicesMapper.updateByPrimaryKeySelective(updateServices);

		//删除多余的SKU
		PmsServicesAttrKeyExample delKeyExample = new PmsServicesAttrKeyExample();
		delKeyExample.createCriteria().andServicesIdEqualTo(services.getId()).andIdNotIn(extraDelKeyId);
		servicesAttrKeyMapper.deleteByExample(delKeyExample);

		PmsServicesAttrValExample delValExample = new PmsServicesAttrValExample();
		delValExample.createCriteria().andServicesIdEqualTo(services.getId()).andAttrKeyIdNotIn(extraDelKeyId);
		servicesAttrValMapper.deleteByExample(delValExample);

		PmsServicesSkuExample skuExample = new PmsServicesSkuExample();
		skuExample.createCriteria().andServicesIdEqualTo(services.getId()).andAttrSymbolPathNotIn(extraDelSku);
		servicesSkuMapper.deleteByExample(skuExample);
	}

	private PmsServicesAttrKey getServicesAttrKey(Integer servicesId, String attrKey){
		if(servicesId == null){
			return null;
		}
		PmsServicesAttrKeyExample example = new PmsServicesAttrKeyExample();
		example.createCriteria().andServicesIdEqualTo(servicesId).andNameEqualTo(attrKey);
		List<PmsServicesAttrKey> list = servicesAttrKeyMapper.selectByExample(example);
		return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
	}

	private PmsServicesAttrVal getServicesAttrValue(Integer servicesId, Integer attrId, String attrValue){
		if(servicesId == null || attrId == null){
			return null;
		}
		PmsServicesAttrValExample example = new PmsServicesAttrValExample();
		example.createCriteria().andServicesIdEqualTo(servicesId).andAttrKeyIdEqualTo(attrId).andValueEqualTo(attrValue);
		List<PmsServicesAttrVal> list = servicesAttrValMapper.selectByExample(example);
		return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
	}

	private PmsServicesSku getServicesSku(Integer servicesId, String attrSymbolPath){
		if(servicesId == null){
			return null;
		}
		PmsServicesSkuExample example = new PmsServicesSkuExample();
		example.createCriteria().andServicesIdEqualTo(servicesId).andAttrSymbolPathEqualTo(attrSymbolPath);
		List<PmsServicesSku> list = servicesSkuMapper.selectByExample(example);
		return CollectionUtil.isNotEmpty(list) ? list.get(0) : null;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void shangjiaServices(List<Integer> servicesIdList) {
		PmsServicesExample example = new PmsServicesExample();
		example.createCriteria().andIdIn(servicesIdList);

		PmsServices updateServices = new PmsServices();
		updateServices.setStatus(ServicesEnums.ServicesStatus.SELL.getValue());
		servicesMapper.updateByExampleSelective(updateServices, example);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void xiajiaServices(List<Integer> servicesIdList) {
		PmsServicesExample example = new PmsServicesExample();
		example.createCriteria().andIdIn(servicesIdList);

		PmsServices updateServices = new PmsServices();
		updateServices.setStatus(ServicesEnums.ServicesStatus.IN_WAREHOUSE.getValue());
		servicesMapper.updateByExampleSelective(updateServices, example);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void deleteServices(List<Integer> servicesIdList) {
		PmsServicesExample example = new PmsServicesExample();
		example.createCriteria().andIdIn(servicesIdList);

		PmsServices updateServices = new PmsServices();
		updateServices.setStatus(ServicesEnums.ServicesStatus.DEL.getValue());
		servicesMapper.updateByExampleSelective(updateServices, example);
	}

	@Override
	public PmsServices getServices(Integer servicesId) {
		PmsServicesExample example = new PmsServicesExample();
		example.createCriteria().andIdEqualTo(servicesId).andStatusNotEqualTo(ServicesEnums.ServicesStatus.DEL.getValue());
		List<PmsServices> servicesList = servicesMapper.selectByExampleWithBLOBs(example);
		return CollectionUtil.isNotEmpty(servicesList) ? servicesList.get(0) : null;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void reduceStock(Integer skuId, Integer num) {
		baseMapper.update("update pms_services_sku set stock = stock-"+ num +" where id = "+skuId);
		//如果库存小于0， 则更新为0
		PmsServicesSkuExample example = new PmsServicesSkuExample();
		example.createCriteria().andIdEqualTo(skuId).andStockLessThan(0);
		PmsServicesSku updateSku = new PmsServicesSku();
		updateSku.setStock(0);
		servicesSkuMapper.updateByExampleSelective(updateSku, example);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void addStock(Integer skuId, Integer num) {
		baseMapper.update("update pms_services_sku set stock = stock+"+ num +" where id = "+skuId);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void updateServices(PmsServices services) {
		services.setUpdTime(DateUtil.date());
		servicesMapper.updateByPrimaryKeyWithBLOBs(services);
	}

	@Override
	public ServicesResult getServicesResult(Integer servicesId) {
		ServicesResult result = new ServicesResult();
		result.setServices(this.getServices(servicesId));

		//拼团规则
		PmsServicesGroupExample groupExample = new PmsServicesGroupExample();
		groupExample.setOrderByClause("num asc");
		groupExample.createCriteria().andServicesIdEqualTo(servicesId);
		result.setServicesGroupList(servicesGroupMapper.selectByExample(groupExample));

		//Sku组合
		//attrKeyList: [{"attrKey":"颜色","attrValue":"","attrValueList":["黑","白"]},{"attrKey":"尺寸","attrValue":"","attrValueList":["大","小"]}]
		//skuList: [["黑","大","","222","999","888","",""],["黑","小","","222","999","888","",""],["白","大","","222","999","888","",""],["白","小","","222","999","888","",""]]
		List<PmsServicesAttrKey> keyList = this.getServicesAttrKeyList(servicesId);

		List<ServicesAttrKeyResult> keyResultList = new ArrayList<>();
		for(PmsServicesAttrKey attrKey : keyList){
			List<PmsServicesAttrVal> valList = this.getServicesAttrValueList(attrKey.getId());

			ServicesAttrKeyResult keyResult = new ServicesAttrKeyResult();
			keyResult.setAttrKey(attrKey.getName());
			keyResult.setAttrValueList(JSONArray.toJSONString(valList.stream().map(PmsServicesAttrVal::getValue).collect(Collectors.toList())));
			keyResultList.add(keyResult);
		}
		result.setAttrKeyList(JSONArray.toJSONString(keyResultList));

		List<PmsServicesSku> skuList = this.getPmsServicesSkuList(servicesId);
		List<List<String>> skuListArray = new ArrayList<>();
		for(PmsServicesSku sku : skuList){
			List<String> skuArray = new ArrayList<>(Arrays.asList(sku.getAttrSymbolName().split(CommonConstant.SLASH_REGEX)));
			skuArray.add(sku.getOriPrice().toString());
			skuArray.add(sku.getPrice().toString());
			skuArray.add(sku.getStock().toString());
			skuArray.add(sku.getWeight().toString());
			skuArray.add(sku.getSkuNo());
			skuArray.add(sku.getImg());
			skuListArray.add(skuArray);
		}
		result.setSkuList(JSONArray.toJSONString(skuListArray));
		return result;
	}

	@Override
	public ServicesSkuResult getServicesSkuList(Integer servicesId) {
		ServicesSkuResult result = new ServicesSkuResult();
		List<PmsServicesAttrKey> keyList = this.getServicesAttrKeyList(servicesId);

		List<ServicesAttrKeyResult> keyResultList = new ArrayList<>();
		for(PmsServicesAttrKey attrKey : keyList){
			List<PmsServicesAttrVal> valList = this.getServicesAttrValueList(attrKey.getId());

			ServicesAttrKeyResult keyResult = new ServicesAttrKeyResult();
			keyResult.setAttrKey(attrKey.getName());
			keyResult.setValList(valList);
			keyResultList.add(keyResult);
		}
		result.setAttrKeyResultList(keyResultList);

		List<PmsServicesSku> skuList = this.getPmsServicesSkuList(servicesId);
		result.setSkuList(skuList);
		return result;
	}

	@Override
	public PmsServicesSku getServicesSku(Integer skuId) {
		return servicesSkuMapper.selectByPrimaryKey(skuId);
	}

	@Override
	public List<PmsServicesGroup> getServicesGroupList(Integer servicesId) {
		PmsServicesGroupExample groupExample = new PmsServicesGroupExample();
		groupExample.setOrderByClause("num asc");
		groupExample.createCriteria().andServicesIdEqualTo(servicesId);
		return servicesGroupMapper.selectByExample(groupExample);
	}

	@Override
	public PmsServicesGroup getServicesGroup(Integer groupId) {
		return servicesGroupMapper.selectByPrimaryKey(groupId);
	}

	@Override
	public List<ServicesStockResult> getServicesStockList(ServicesSearchForm form, Integer page, Integer pageSize) {
		PageHelper.startPage(page, pageSize);
		return customServicesMapper.getServicesStockList(form);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public void updateServicesStock(List<PmsServicesSku> stockList) {
		for(PmsServicesSku sku : stockList) {
			PmsServicesSku updateSku = new PmsServicesSku();
			updateSku.setId(sku.getId());
			updateSku.setStock(sku.getStock());
			servicesSkuMapper.updateByPrimaryKeySelective(updateSku);
		}
	}

	@Override
	public void synStock(Integer shopId) {
		//查询仓库所有库存
		TradeStorageStockExample example = new TradeStorageStockExample();
		example.createCriteria().andShopIdEqualTo(shopId);
		List<TradeStorageStock> stockList = tradeStorageStockMapper.selectByExample(example);
		if(CollectionUtil.isNotEmpty(stockList)) {
			for(TradeStorageStock stock : stockList) {
				PmsServicesSku updateSku = new PmsServicesSku();
				updateSku.setId(stock.getSkuId());
				updateSku.setStock(stock.getStock());
				servicesSkuMapper.updateByPrimaryKeySelective(updateSku);
			}
		}

	}

	@Override
	public List<ServicesExportResult> getExportList(ServicesSearchForm form, Integer page, Integer pageSize) {
		List<PmsServices> servicesList = this.getServicesList(form, page, pageSize);
		if(CollectionUtil.isEmpty(servicesList)) {
			return null;
		}
		List<Integer> servicesIds = servicesList.stream().map(PmsServices::getId).collect(Collectors.toList());

		PmsServicesSkuExample example = new PmsServicesSkuExample();
		example.setOrderByClause("id asc");
		example.createCriteria().andServicesIdIn(servicesIds);
		List<PmsServicesSku> skuList = servicesSkuMapper.selectByExample(example);
		Map<Integer, List<PmsServicesSku>> skuMap = skuList.stream().collect(Collectors.groupingBy(PmsServicesSku::getServicesId));

		List<ServicesExportResult> list = new ArrayList<>();
		for(PmsServices services : servicesList) {
			ServicesExportResult result = new ServicesExportResult();
			BeanUtil.copyProperties(services, result);
			result.setSkuList(skuMap.get(services.getId()));
			list.add(result);
		}
		return list;
	}

	@Override
	public void importServices(UmsShop shop, Integer freightId, List<ServicesImportForm> servicesList) {
		Map<String, Integer> cateMap = new HashMap<>();
		for(ServicesImportForm form : servicesList) {
			form.setShopId(shop.getId());
			form.setShopName(shop.getName());
			form.setType(ServicesEnums.ServicesType.NORMAL_GOODS.getValue());
			form.setStatus(ServicesEnums.ServicesStatus.SELL.getValue());
			form.setFreightTemplateId(freightId);
			form.setPrice(new BigDecimal(form.getPrices().split(CommonConstant.SLASH_REGEX)[0]));
			String[] cateNames = form.getCateName().split(CommonConstant.SLASH_REGEX);
			List<Integer> cateIds = new ArrayList<>();
			form.setCatePid(this.getCateIdByName(cateMap, cateNames[0], 0));
			cateIds.add(form.getCatePid());
			if(cateNames.length >=2 ){
				form.setCateTid(this.getCateIdByName(cateMap, cateNames[1], form.getCatePid()));
				cateIds.add(form.getCateTid());
			}
			if(cateNames.length >=3){
				form.setCateId(this.getCateIdByName(cateMap, cateNames[2], form.getCateTid()));
				cateIds.add(form.getCateId());
			}
			form.setCateIds(StringUtils.join(cateIds, ","));
			form.setSort(9999);
//			form.setWeight(0);
			form.setUpdTime(DateUtil.date());
		}
		customServicesMapper.insertServicesList(servicesList);

		for(ServicesImportForm form : servicesList) {
			PmsServicesAttrKey servicesAttrKey = new PmsServicesAttrKey();
			servicesAttrKey.setServicesId(form.getId());
			servicesAttrKey.setName("规格");
			servicesAttrKeyMapper.insertSelective(servicesAttrKey);

			PmsServicesAttrVal servicesAttrVal = new PmsServicesAttrVal();
			servicesAttrVal.setServicesId(form.getId());
			servicesAttrVal.setAttrKeyId(servicesAttrKey.getId());
			servicesAttrVal.setAttrKeyName(servicesAttrKey.getName());
			servicesAttrVal.setValue("默认");
			servicesAttrValMapper.insertSelective(servicesAttrVal);

			PmsServicesSku sku = new PmsServicesSku();
			sku.setServicesId(form.getId());
			sku.setAttrSymbolPath(servicesAttrVal.getId().toString());
			sku.setAttrSymbolName(servicesAttrVal.getValue());
			sku.setPrice(form.getPrice());
			sku.setOriPrice(sku.getPrice());
			sku.setStock(1000);
			sku.setImg(form.getMainImg());
			servicesSkuMapper.insertSelective(sku);
		}
	}


	private Integer getCateIdByName(Map<String, Integer> cateMap, String name, Integer parentId) {
		if(cateMap.get(name+"-"+parentId) != null) {
			return cateMap.get(name+"-"+parentId);
		}else {
			//创建新分类
			Integer cateId = servicesCateService.addServicesCate(parentId == 0 ? null : parentId, name, 99, null, null);
			cateMap.put(name+"-"+parentId, cateId);
			return cateId;
		}
	}

	private List<PmsServicesAttrKey> getServicesAttrKeyList(Integer servicesId){
		PmsServicesAttrKeyExample keyExample = new PmsServicesAttrKeyExample();
		keyExample.setOrderByClause("id asc");
		keyExample.createCriteria().andServicesIdEqualTo(servicesId);
		return servicesAttrKeyMapper.selectByExample(keyExample);
	}

	private List<PmsServicesAttrVal> getServicesAttrValueList(Integer attrKeyId){
		PmsServicesAttrValExample valExample = new PmsServicesAttrValExample();
		valExample.setOrderByClause("id asc");
		valExample.createCriteria().andAttrKeyIdEqualTo(attrKeyId);
		return servicesAttrValMapper.selectByExample(valExample);
	}

	private List<PmsServicesSku> getPmsServicesSkuList(Integer servicesId){
		PmsServicesSkuExample skuExample = new PmsServicesSkuExample();
		skuExample.setOrderByClause("id asc");
		skuExample.createCriteria().andServicesIdEqualTo(servicesId);
		return servicesSkuMapper.selectByExample(skuExample);
	}
}
